var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var multer = require('multer');
var tool = require('./util/tools');

var app = express();

/* session模块 */
app.use(session({
    resave: true,
    saveUninitialized: false,
    secret: 'taller',
    cookie:{
        maxAge: 1000*60*60 // 默认有效时间是1小时
    },
}));
app.use(function(req, res, next){
    req.session._garbage = Date();
    req.session.touch();
    next();
});

/* 读取请求中的body */
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer());

/* 模板引擎 */
app.use(express.static('public'));
app.set('view engine','ejs');
app.use(express.static(__dirname+'/views'));

/* 引入路由 */
var comm = require('./routes/common');
var menu = require('./routes/menu');
var desktop = require('./routes/desktop');
var department = require('./routes/department');
var users = require('./routes/users');
var role = require('./routes/role');
var devices = require('./routes/devices');

app.use('/login', comm);
//中间件主要用于权限判断
app.use(function (req, res, next) {
    var path = req.path;
    path = path.substring(1,path.length);
    console.log('req:', req.path);
    console.log('Time:', Date.now());
    //路由权限控制
    if((typeof comm[path]) == 'undefined'){
        try{
            if((typeof req.session.user.id) == 'undefined' ){
                console.log('status:', 'no login');
                res.redirect('/login/auth');
                return;
            }
        }catch (e){
            res.redirect('/login/auth');
            return;
        }

    }
    //在数据中加入创建时间、创建人、修改时间、修改人
    if(tool.isHave(path,'/opt/0')){
        req.body = tool.addObj(req.body,req.session.user,1);
    }else {
        req.body = tool.addObj(req.body,req.session.user,2);
    }
    //
    next();
});
app.use('/desktop', desktop);
app.use('/core/menu', menu);
app.use('/core/department', department);
app.use('/core/users', users);
app.use('/core/role', role);
app.use('/business/devices',devices);


app.listen(8010);
